package com.ruoyi.business.util;

import com.alibaba.fastjson.JSON;
import com.ruoyi.business.dto.TicketDTO;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class PythonUtil {

    public static TicketDTO getSymbolCurrData(String symbol) {
        try {
            List<TicketDTO> ticketDTOS = new ArrayList<>();
            // 指定Python解释器路径和Python脚本路径
            String[] args1 = new String[]{"python", "D:\\pythoFile\\sub_tick_manual.py", symbol};//第二个为python脚本所在位置，后面的为所传参数（得是字符串类型）
            Process process = Runtime.getRuntime().exec(args1);

            // 读取Python脚本的输出
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(), "gb2312"));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));

            // 输出Python脚本的标准输出和标准错误
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
                ticketDTOS = JSON.parseArray(s, TicketDTO.class);
                if (!CollectionUtils.isEmpty(ticketDTOS)) {
                    System.out.println("获取标的最新数据" + ticketDTOS.get(0).toString());
                }
            }
            while ((s = stdError.readLine()) != null) {
                System.err.println(s);
            }

            // 等待Python脚本执行完毕并获取退出状态
            int exitCode = process.waitFor();
            System.out.println("\nExited with error code : " + exitCode);

            return ticketDTOS.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
